﻿using System;
using System.Collections.Generic;
using OhioState.AssetManaged;

namespace OhioState.Graphics.OpenGL
{
    public class FrameBufferObjectHandler : OpenGLObject, IFrameBufferObject
    {
        public FrameBufferObjectHandler(IFrameBufferObject proxy)
            : base(proxy as IAssetManaged)
        {
            fboProxy = proxy;
        }

        #region IFrameBufferObject Members
        public IDepthBuffer DepthBuffer
        {
            get { return fboProxy.DepthBuffer; }
        }

        public FrameBufferClear ClearFlags
        {
            get { return fboProxy.ClearFlags; }
        }

        public void Disable(IRenderPanel panel)
        {
            realFBO.Disable(panel);
        }

        public void Enable(IRenderPanel panel)
        {
            if (!created)
            {
                Create(panel);
            }
            if (this.Invalid)
            {
                UpdateFBO(panel);
            }
            realFBO.Enable(panel);
        }

        public IList<ITexture> Textures
        {
            get { return fboProxy.Textures; }
        }
        #endregion

        private void Create(IRenderPanel panel)
        {
            IList<ITexture> renderTextureProxies = fboProxy.Textures;
            IList<ITexture> renderTextures = new List<ITexture>(renderTextureProxies.Count);
            foreach (ITexture texture in renderTextureProxies)
            {
                ITexture tex2DHandler = panel.ResourceManager.GetItem(texture as IAssetManaged) as ITexture;
                renderTextures.Add(tex2DHandler);
            }
            IDepthBuffer depthBuffer = fboProxy.DepthBuffer;
            if (depthBuffer != null)
            {
                depthBuffer = panel.ResourceManager.GetItem(depthBuffer as IAssetManaged) as IDepthBuffer;
            }
            realFBO = new FrameBufferObjectGL(renderTextures, depthBuffer, fboProxy.ClearFlags);
            created = true;
        }

        private void UpdateFBO(IRenderPanel panel)
        {
            IDisposable disposable = realFBO as IDisposable;
            if (disposable != null)
                disposable.Dispose();
            Create(panel);
            this.Invalid = false;
        }

        private IFrameBufferObject fboProxy;
        private IFrameBufferObject realFBO;
        private bool created = false;
    }
}
